package com.txby.platformCore.component.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.ProtoCommon;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;

import com.jck.tools.FileUtils;

/**
 * FastDFS功能调用类
 * 
 */
public class FastDFSUtil {
	private static Logger log = Logger.getLogger(FastDFSUtil.class);
    private static StorageClient1 storageClient1 = null;
	  // 初始化FastDFS Client
    static {
        try {
			// 初始化配置文件
        	URL fileUrl = FastDFSUtil.class.getResource("/fdfs_client.conf");
			ClientGlobal.init(fileUrl.getPath());
            TrackerClient trackerClient = new TrackerClient(ClientGlobal.g_tracker_group);
            TrackerServer trackerServer = trackerClient.getConnection();
            if (trackerServer == null) {
                throw new IllegalStateException("getConnection return null");
            }

            StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
            if (storageServer == null) {
                throw new IllegalStateException("getStoreStorage return null");
            }
            storageClient1 = new StorageClient1(trackerServer,storageServer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	
	/**
	 * 获取token
	 * @param fileId
	 * @param filename
	 * @return
	 * @throws Exception
	 */
    public static String getToken(String fileId,String filename) throws Exception {
    	String[] results = new String[2];
		int errno = StorageClient1.split_file_id(fileId, results);
		if(errno != 0){
			throw new Exception("fileId格式错误!");
		}
		//以秒为单位  
		int ts = (int)(System.currentTimeMillis()/1000);
		String token = ProtoCommon.getToken(results[1], ts, ClientGlobal.getG_secret_key());
		StringBuilder sb = new StringBuilder();
		sb.append("token=").append(token);
	    sb.append("&ts=").append(ts);
		return sb.toString();
    }

	/**
	 * 上传文件
	 * 
	 * @return
	 */
	public static String[] uploadFile(String fileName, String fileExt, byte[] contents) {
		try {
			if (fileName == null || contents == null) {
				log.debug("Upload file[" + fileName + "] is null");
				return null;
			}

			long startTime = System.currentTimeMillis();
			log.debug("Upload file[" + fileName + "] startTime::" + startTime);
			NameValuePair[] meta_list = new NameValuePair[1];
			meta_list[0] = new NameValuePair("filename", fileName);
			String[] fileInfo = storageClient1.upload_file(contents, fileExt, meta_list);

			log.debug("Upload file[" + fileName + "] ok");
			log.debug(fileInfo[0]);// 文件存储所在的组 如：group1 group2等
			log.debug(fileInfo[1]);// 文件在服务器上的路径及文件名
			// 如：M00/00/00/eWXds1DJpzCASX0oAAAAA4i3nNI382.txt

			long endTime = System.currentTimeMillis();
			log.debug("Upload file[" + fileName + "] endTime::" + endTime);
			return fileInfo;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 删除文件
	 * 
	 * @param groupName
	 * @param fileName
	 * @return
	 */
	public static Integer deleteFile(String groupName, String fileName) {
		try {
			long startTime = System.currentTimeMillis();
			log.debug("Delete file[" + fileName + "] startTime::" + startTime);
			// 建立存储客户端
			Integer x = storageClient1.delete_file(groupName, fileName);
			log.debug("Delete file[" + fileName + "] ok");
			long endTime = System.currentTimeMillis();
			log.debug("Delete file[" + fileName + "] endTime::" + endTime);
			return x;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}  finally {
		}
		return 0;
	}

	/**
	 * 下载文件
	 * 
	 * @param groupName
	 * @param fileName
	 * @return
	 */
	public static byte[] downloadFile(String groupName, String fileName) {
		try {
			long startTime = System.currentTimeMillis();
			log.debug("Download file[" + fileName + "] startTime::" + startTime);
			byte[] localfileByteArr = storageClient1.download_file(groupName, fileName);
			return localfileByteArr;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
		return null;
	}

	 /**
     * 获取文件元数据
     * @param fileId 文件ID
     * @return
     */
    public static Map<String,String> getFileMetadata(String fileId) {
        try {
            NameValuePair[] metaList = storageClient1.get_metadata1(fileId);
            if (metaList != null) {
                HashMap<String,String> map = new HashMap<String, String>();
                for (NameValuePair metaItem : metaList) {
                    map.put(metaItem.getName(),metaItem.getValue());
                }
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

	
	public static void main(String[] args) {
		try {
/*			group1
			M00/00/00/rBF_CVnuzAqAImuQAABFRlP2djE620.txt
			2cb6ad6515ddd66819828f8432c4b134
			*/
//			downloadFile("group1","M00/00/00/rBF_CVnuzAqAImuQAABFRlP2djE620.txt");
//			deleteFile("group1","M00/00/00/rBF_CVnuzAqAImuQAABFRlP2djE620.txt");
			String fileName = "test";
			String fileExt = "jpg";
			File file = new File("D:\\test.jpg");
			String str[]=uploadFile(fileName, fileExt, FileUtils.readFileToByteArray(file));
			System.out.println(str[0]);
			System.out.println(str[1]);
			try {
				System.out.println(getToken(str[0]+"/"+str[1], ""));
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
